package com.marcocirillo.justweet;

import java.io.*;
import java.util.Scanner;

import javax.swing.*;

public class GUI {
	
	private static File settings;
	private static JusTweet jt;
	

	
	private static JusTweet getAccount(File settingsFile)
    {
		String[] credentials = new String[2]; // 2 lines, one for username, one for password.
		Scanner fileInput = null; //keep compiler happy.
		try
	    {
	    	fileInput = new Scanner(settingsFile);
	    } catch (FileNotFoundException e)
	    {
	    	e.printStackTrace();
	    	JOptionPane.showMessageDialog(new JDialog(), "File Not Found, please submit a bug!", "FileNotFound Error!", JOptionPane.ERROR_MESSAGE);
	    	System.exit(1);
	    }
	    
	    for (int i = 0; fileInput.hasNextLine(); i++)
	    {
	    	try
	    	{
	    		credentials[i] = fileInput.nextLine();
	    	} catch (IndexOutOfBoundsException e)
	    	{
	    		JOptionPane.showMessageDialog(new JDialog(), "JusTweet.ini should only have 2 lines!", "JusTweet.ini is Corrupt!", JOptionPane.ERROR_MESSAGE);
	    	}
	    	
	    }
	    
	    JusTweet jt = new JusTweet(credentials[0], credentials[1]);
	    return jt;
	    
    }

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		jt = null;
		
	    /* Check for ini file */
	    settings = new File("JusTweet.ini");
	    if (!settings.exists())
	    {
	    	boolean isFileCreated = false; // initiate as false to keep compiler happy
	    	try
	    	{
	    		isFileCreated = settings.createNewFile();
	    	} catch (IOException e)
	    	{
	    		e.printStackTrace();
	    	}
	    	if (isFileCreated)
	    	{
	    		System.out.println("File created succesfully.");
	    		LoginWindow lw = new LoginWindow(500,300,jt);
	    		lw.setVisible(true);
	    	} else
	    		
	    	{
	    		System.out.println("File create failed.");
	    	}
	    	
	    	
	    } else
	    {  //settings exist, lets import.
	    	jt = getAccount(settings);
	    	if (!jt.isAuthenticated())
	    	{
	    		jt = null;
	    		JOptionPane.showMessageDialog(new JDialog(), "Invalid username/password. We will delete JusTweet.ini so you can try again", "Authentification Failed!", JOptionPane.ERROR_MESSAGE);
	    		settings.delete();
	    		LoginWindow lw = new LoginWindow(500,300,jt);
	    		lw.setVisible(true);
	    	}
	    	View v = new View(500, 300, jt);
	    	v.setVisible(true);
	    		
	    }
	   /* System.out.println("About to create WIndow");
		View v = new View(500, 300, jt);
		v.setVisible(true);*/
		
	}
	
	/*public void setJusTweet(JusTweet jt)
	{
		this.jt = jt;
	}*/

}
